package com.answerz.module_reportissues.viewmodel

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import androidx.databinding.ObservableField
import com.annimon.stream.Collectors
import com.annimon.stream.Stream
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.*
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.luck.picture.lib.adapter.GridImageAdapter
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.vincent.videocompressor.VideoCompress
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class ComplaintSubmitViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var reportTypeId= ObservableField(-1)
    var reportContent= ObservableField("")
    var submitSuccessEvent: SingleLiveEvent<Void> = SingleLiveEvent()
    var onClickSubmit: BindingCommand<Void> = BindingCommand(BindingAction {
        submitReport()
    })

    //    val startUploadEvent:SingleLiveEvent<Void> = SingleLiveEvent()
    val uploadImgEvent: SingleLiveEvent<UploadImgEventBean> = SingleLiveEvent()
    @SuppressLint("SimpleDateFormat")
    fun uploadImgAndVideo(fromIndex:Int, fileList:ArrayList<LocalMedia>, context: Context){
//        Thread.sleep(3000)
        if (fromIndex< fileList.size){
            fileList[fromIndex].imageState= GridImageAdapter.STATE_LOADING
            uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
            if (TextUtils.isEmpty(fileList[fromIndex].remotePath)){
                if (PictureMimeType.isHasVideo(fileList[fromIndex].mimeType)){
                    if (TextUtils.isEmpty(fileList[fromIndex].compressPath)){
                        var externalFilesDir=context.getExternalFilesDir(Environment.DIRECTORY_MOVIES)
                        var customFile= File(externalFilesDir,"cache")
                        if (!customFile.exists()) {
                            customFile.mkdirs();
                        }
                        var destPath=customFile.absolutePath+ File.separator + "VID_" + SimpleDateFormat(
                            "yyyyMMdd_HHmmss"
                        ).format(
                            Date()
                        ) + ".mp4"
                        VideoCompress.compressVideoLow(fileList[fromIndex].realPath,destPath,object :
                            VideoCompress.CompressListener {
                            override fun onStart() {
                                Log.e("ReportSubmitViewmodel","--------------------------onStart")
                            }

                            override fun onSuccess() {
                                dismissLoading()
                                fileList[fromIndex].compressPath=destPath
                                fileList[fromIndex].imageState= GridImageAdapter.STATE_LOADING
                                uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                                uploadImg(fromIndex,fileList,context)
                                Log.e("ReportSubmitViewmodel","--------------------------onSuccess")
                            }

                            override fun onFail() {
                                fileList[fromIndex].imageState= GridImageAdapter.STATE_FAIL
                                uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                                dismissLoading()
                                uploadImgAndVideo(fromIndex+1,fileList,context)
                                Log.e("ReportSubmitViewmodel","--------------------------onFail")
                            }

                            override fun onProgress(percent: Float) {
                                Log.e("ReportSubmitViewmodel","--------------------------百分之"+percent)
                            }

                        })
                    }else{
                        uploadImg(fromIndex,fileList,context)
                    }
                }else{
                    uploadImg(fromIndex,fileList,context)
                }
            }else{
                fileList[fromIndex].imageState= GridImageAdapter.STATE_NORMAL
                uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                uploadImgAndVideo(fromIndex+1,fileList,context)
            }
        }
    }
    fun uploadImg(fromIndex:Int, fileList:ArrayList<LocalMedia>, context: Context){
        model.uploadHeadImg("gongdan",fileList[fromIndex].compressPath,"")
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe{}
            .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>(){
                override fun onResult(t: BaseBean<ImgRspBean>) {
                    dismissLoading()
                    if (t.code==200){
                        fileList[fromIndex].remotePath= t.data!!.url
                        fileList[fromIndex].imageState= GridImageAdapter.STATE_NORMAL
                        uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                    }else{
                        showErrorToast(t.msg)
                        fileList[fromIndex].imageState= GridImageAdapter.STATE_FAIL
                        uploadImgEvent.postValue(UploadImgEventBean(fromIndex,false,fileList))
                    }
                    uploadImgAndVideo(fromIndex+1,fileList,context)
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                    fileList[fromIndex].imageState= GridImageAdapter.STATE_FAIL
                    uploadImgEvent.postValue(UploadImgEventBean(fromIndex,false,fileList))
                    uploadImgAndVideo(fromIndex+1,fileList,context)
                }

            })
    }
    var localFiles= ObservableField<ArrayList<LocalMedia>>(ArrayList())
    private fun submitReport() {
        if (localFiles.get()!=null&& localFiles.get()!!.isNotEmpty()){
            for (item in localFiles.get()!!){
                if (item.imageState== GridImageAdapter.STATE_LOADING ||item.imageState== GridImageAdapter.STATE_WAIT_LOADING){
                    showNormalToast("请等待图片上传完成")
                    return
                }
            }
        }
        if (TextUtils.isEmpty(reportContent.get().toString())){
            showNormalToast("请描述问题")
            return
        }
        var files=ArrayList<String>()
        if (localFiles.get()!=null&& localFiles.get()!!.isNotEmpty()){
            for (item in localFiles.get()!!){
                if (item.imageState!= GridImageAdapter.STATE_FAIL &&!TextUtils.isEmpty(item.remotePath)){
                    files.add(item.remotePath)
                }
            }
        }
        var com=ComplaintSubmitRequestBean(model.getAreaId(),reportContent.get().toString(),files,6)
        model.submitComplaint(com).compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object: ApiSubscriberHelper<BaseBean<Any?>>(){
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code==200){
                        showSuccessToast("提交成功！")
                        submitSuccessEvent.call()
                    }else{
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }


    public fun reportContentLength(content:String): String {
        return content.length.toString()+"/150"
    }
}